package com.qf.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.common.lang.Result;
import com.qf.dao.UserMapper;
import com.qf.dto.ChangePersonalInfoDto;
import com.qf.dto.ChangePswDto;
import com.qf.dto.LoginDto;
import com.qf.dto.RegisterDto;
import com.qf.entity.User;
import com.qf.response.BaseException;
import com.qf.response.ResponseCode;
import com.qf.service.IUserService;
import com.qf.util.RedisUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author astupidcoder
 * @since 2021-06-08
 */
@RestController
@RequestMapping("/jjshipping/user")
public class UserController {

    @Resource
    UserMapper userMapper;
    @Autowired
    IUserService iUserService;
    @Autowired
    RedisUtils redisUtils;


    /**
     * 注册
     */
    @PostMapping("/register")
    public Result register(@Param("RegisterDto") RegisterDto registerDto,String vCode) {
        System.out.println(vCode);
        String code=(String) redisUtils.get("registerVCode");
        if(!code.equalsIgnoreCase(vCode))throw new BaseException(ResponseCode.VCODE_ERROR);
        Result result = new Result();
        QueryWrapper wrapper = new QueryWrapper();
        System.out.println("registerDto = " + registerDto);
        //查询账户是否已经注册
        wrapper.eq("userName", registerDto.getUserName());
        User user = userMapper.selectOne(wrapper);
        System.out.println("user = " + user);

        if (user != null) {
            System.out.println("users = " + user);
            return result.fail("账号已被注册！");

        } else {
            //创建user
            User user1 = new User();
            System.out.println("user1 = " + user1);
            System.out.println("registerDto.getUserName() = " + registerDto.getUserName());
            //赋值
            user1.setUserName(registerDto.getUserName());
            user1.setPassWord(registerDto.getPassWord());
            user1.setRealName(registerDto.getRealName());
            user1.setPhoneNumber(registerDto.getPhoneNumber());
            user1.setTelePhone(registerDto.getTelePhone());
            user1.setWeChat(registerDto.getWeChat());
            user1.setQq(registerDto.getQQ());
            user1.setEmail(registerDto.getEmail());
            user1.setZipcode(registerDto.getZipcode());
            user1.setAddress(registerDto.getAddress());
            user1.setCreateTime(LocalDateTime.now());
            user1.setUpdateTime(LocalDateTime.now());
            user1.setIsDelete(0);
            System.out.println("user1 = " + user1);

            //添加新用户
            int b = userMapper.insert(user1);
            if (b == 0) {
                return result.fail("注册失败！");

            }
            return result.succ(200, "注册成功！", user1);


        }


    }


    /**
     * 登入
     *
     * @param userName
     * @param passWord
     * @return
     */
    @PostMapping("/login")
    public Result login(@Param("userName") String userName, @Param("passWord") String passWord,String vCode) {
        String code=(String) redisUtils.get("loginVCode");
        if(!code.equalsIgnoreCase(vCode))throw new BaseException(ResponseCode.VCODE_ERROR);
        Result result = new Result();
        QueryWrapper wrapper = new QueryWrapper();

        //根据前端传过来的的用户名查询用户
        wrapper.eq("userName", userName);
        User user = userMapper.selectOne(wrapper);

        //前端传递过来的账户密码
        System.out.println("userName = " + userName);
        System.out.println("passWord = " + passWord);

        //如果账户不存在 提示账户不存在
        if (user == null) {
            return result.fail("账号未注册");

        }

        //查询得到的用户密码
        System.out.println(user.getPassWord());
        boolean b = user.getPassWord().equals(passWord);
        System.out.println("b = " + b);

        //如果用户已注册 查询账户密码 判断账户密码是佛正确
        if (b) {
            String token= UUID.randomUUID().toString();
            redisUtils.sSetAndTime(token,3600*24*3,user);
            Map<String,String> map=new HashMap<>();
            map.put("token",token);
            map.put("userId",user.getId()+"");
            map.put("uid",user.getUserName());
            map.put("userName",user.getRealName());
            return result.succ(200, "登入成功", map);

        } else {
            return result.fail("账号或密码错误");

        }


    }
    /**
     * 获取用户的数据
     */
    @GetMapping("/getUser")
    public Result getUser(Integer id){
        return Result.succ(iUserService.getById(id));
    }
    /**
     * 修改密码
     *
     * @param changePswDto
     * @return
     */
    @PostMapping("/changePsw")
    public Result changePassword(ChangePswDto changePswDto) {

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("userName", changePswDto.getUserName());

        //判断用户名是否存在
        if (iUserService.getOne(wrapper) == null) {
            //1.为空
            return new Result().fail("用户未注册");
        }


        //判断用户密码是否正确
        User user_q = new User();
        user_q.setUserName(changePswDto.getUserName());
        user_q.setPassWord(changePswDto.getPassWord());//旧密码

        User user_query = iUserService.getOne(new QueryWrapper<User>(user_q));
        if (user_query == null) {
            return new Result().fail("账户或者密码错误");

        }


        //修改密码
        User user_new = new User();
        user_new.setUserName(changePswDto.getUserName());
        user_new.setPassWord(changePswDto.getNewPsw());//旧密码

        //修改并判断是否成功
        boolean isSucc = iUserService.update(user_new, new QueryWrapper<User>(user_q));
        System.out.println("isSucc = " + isSucc);
        if (isSucc) {
            //成功
            User uu = iUserService.getOne(new QueryWrapper<User>(user_new));
            return new Result().succ(null);

        } else {
            return new Result().fail("失败");

        }
    }


    /**
     * 用户修改个人信息
     * 用户账户密码要正确才能修改
     * @param user
     * @return
     */
    @PostMapping("/changePersonalInfo")
    public Result changePersonalInfo(User user) {
        //System.out.println("cpid = " + cpid);
//        /*
//        * 判读用户是否存在
//        * */
//        HashMap<String, String> hm = new HashMap<>();
//        //放入元素
//        hm.put("userName", cpid.getUserName());
//        hm.put("passWord", cpid.getPassWord());
//
//        User u_exit = iUserService.getOne(new QueryWrapper<User>().allEq(hm));
//
//        if (u_exit == null) {
//            return new Result().fail("用户不存在");
//        }
//
//        /**
//         *
//         * 用户存在继续实行 更新数据
//         */
//        //最新信息
//        User user1 = new User();
//        user1.setUserName(cpid.getUserName());
//        user1.setPassWord(cpid.getPassWord());
//        user1.setRealName(cpid.getRealName());
//        user1.setPhoneNumber(cpid.getPhoneNumber());
//        user1.setEmail(cpid.getEmail());
//        user1.setWeChat(cpid.getWeChat());
//        user1.setQq(cpid.getQq());
//
//
//        // 查询指定用户 并更新信息     同时判断是否成功  =>用户名密码正确 才能修改
//        boolean b = iUserService.update(user1, new QueryWrapper<User>().allEq(hm));
//        System.out.println("b = " + b);
        boolean b = iUserService.updateById(user);
        if (b) {
            return new Result().succ(null);

        } else {
            return new Result().fail("更新失败");

        }
    }


    /**
     * 管理员修改个人信息
     *  userid不变 什么都有修改
     *  若id不存在 则添加新新用户
     * @param cpid
     * @return
     */
    @PostMapping("/changePersonInfoById")
    public Result changePersonInfoById(ChangePersonalInfoDto cpid){
        System.out.println("cpid = " + cpid);
        /**
         *
         * 用户存在继续实行 更新数据
         */
        //最新信息
        User user1 = new User();
        user1.setUserName(cpid.getUserName());
        user1.setPassWord(cpid.getPassWord());
        user1.setRealName(cpid.getRealName());
        user1.setPhoneNumber(cpid.getPhoneNumber());
        user1.setEmail(cpid.getEmail());
        user1.setWeChat(cpid.getWeChat());
        user1.setQq(cpid.getQq());


        // 查询指定用户 并更新信息     同时判断是否成功  =>用户名密码正确 才能修改
        boolean b = iUserService.saveOrUpdate(user1,new QueryWrapper<User>().eq("id",cpid.getId()));
        System.out.println("b = " + b);

        if (b) {
            return new Result().succ(null);

        } else {
            return new Result().fail("更新失败");

        }

    }
    /**
     * 查询所有用户
     *
     * @return
     */
    @GetMapping("/getAllUser")
    public Result getAllUser() {
        iUserService.list();
        if (iUserService.list() == null) {
            return new Result().fail("查询失败");

        }
        return new Result().succ(iUserService.list());

    }


    /**
     * 根据id删除用户
     * @param id
     * @return
     */
    @GetMapping("/delUser")
    public Result delUserById(Integer id) {
       boolean b =  iUserService.removeById(id);
        if (b) {

            return new Result().succ(null);
        }
        return new Result().fail("删除失败！");

    }

    /**
     * 查询所有名字带 username的用户
     * @param userName
     * @return
     */
    @GetMapping("/getUserByName")
    public Result getUserByName(String userName){

        List<User> users = iUserService.list(new QueryWrapper<User>().like("userName", userName));
        if(users == null){
            return new Result().fail("查询失败");

        }
        return new Result().succ(users);
    }




}
